<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Auth;
use App\Services\AdminService;
use Illuminate\Support\Facades\Hash;

class AdminController extends Controller
{

    private $adminService;

    public function __construct(AdminService $adminService)
    {
        $this->adminService = $adminService;
    }

    public function index()
    {
        $admins = AdminUser::query()
                           ->with('role')
                           ->get();

        return $admins;
    }

    public function create(Request $request)
    {
        $body = $request->post();

        $id = $request->query('id', 0);

        $admin = AdminUser::query()
                          ->findOrNew($id);

        $this->validate($request, [
            'username' => 'required',
            'name' => 'required',
            'role_id' => 'required',
        ]);

        $admin->username = $body['username'];
        $admin->name = $body['name'];
        $admin->role_id = $body['role_id'];
        $admin->password = Hash::make('123456');
        $admin->avatar = $body['avatar'] ?? '';

        $admin->save();

        return $admin;
    }

    public function adminHasMenus()
    {
        $admin = AdminUser::query()
                          ->find(Auth::guard('admin')
                                     ->id());

        return $this->adminService->getTree($admin->role->menu->sortBy('order')
                                                              ->toArray());
    }

    public function show(int $id)
    {
        return AdminUser::find($id);
    }

    public function update(int $id, Request $request)
    {
        $body = $request->post();

        $this->validate($request, [
            'password' => 'required',
            'confirm' => 'required',
        ]);

        if ($body['password'] !== $body['confirm']) {
            abort(500, '用户密码与确认密码不一致');
        }

        $admin = AdminUser::query()
                          ->find($id);

        $admin->password = Hash::make($body['password']);

        $admin->save();

        return $admin;
    }
}
